/*
 * 威胁等级模块
 */
define("func/threatLevel", [
    "leaflet",
    "func/base",
    "data/ajax",
    "plugins/flashing",
    "plugins/mcscroll",
    "control/paging",
    "control/panel"
], function (L) {
    L.ICT.Func.add("ThreatLevel", {

        Class: L.Class.extend({

            initialize: function () {
                this.menu = L.ict.app.menu;
                this.menuid = "ict_menu_main_wxdj";
                this.ictmap = L.ict.app.ictmap;
                this.dialog = L.ict.app.util.dialog;
                this.dateTimeUtil = L.ict.app.util.dateTime; // this.util.dateTime.getCurrentUnixTime();
                this.config = Project_ParamConfig.ThreatLevelConfig;
                this.ajax = new L.ICT.Ajax();
                // var startTime = this.config.startTime || L.ict.app.startTime;
                var startTime = Number(L.ict.app.util.dateTime.getCurrentUnixTime() - Project_ParamConfig.RealTargetConfig.timeout * 60);
                this._times = [null, startTime, startTime, startTime, startTime];
                this._ajaxs = [null, new L.ICT.Ajax(), new L.ICT.Ajax(), new L.ICT.Ajax(), new L.ICT.Ajax()];
                this._ajaxCallbacks = [null, this._ajaxCallback1, this._ajaxCallback2, this._ajaxCallback3, this._ajaxCallback4];
                this._detailAjax = new L.ICT.Ajax();
            },

            start: function () {
                if(Project_ParamConfig.CurrentMode !== 0){
                    L.ict.app.util.dialog.warn('提示','此功能仅综合模式下可用!');
                    this.stop();
                    return;
                }
                if (this._container)   return;
                this.menu.mainmenu.deactiveMenuExceptOne(this.menuid);
                this.menu.mainmenu.disableMenuExceptOne(this.menuid);
                this.menu.mainmenu.deactivePortInfo(); //退出港口菜单
                this.ictmap.OperateState.wxpg = true;
                this.ictmap.realtarget.stopInterval();
                this._initVals();
                this._initUI();
                this._initEvts();
                this.sendAjaxOne();
            },

            stop: function () {
                if(this._container) {
                    this._container.remove();
                    this._container = null;
                }
                if(this._popPanel) {
                    this._popPanel.remove();
                    this._popPanel = null;
                }
                this.clearIntervals();
                this.stopAjaxs();
                this.menu.mainmenu.deactiveMenu(this.menuid);
                this.menu.mainmenu.enableMenu();
                this.ictmap.OperateState.wxpg = false;
                this.ictmap.realtarget.getRealTarget();
            },

            _initVals: function () {
                this._curLevel = 0; // 当前打开的等级，枚举值有 0,1,2,3,4
                this._firstCompelete = false;
                this._ajaxCompelets = [null, 0, 0, 0, 0]; // 记录每个ajax请求是否完成
                this._intervals = [null, null, null, null, null]; // 记录每个轮询 setInterval id
                this._resData = [[],[],[],[],[]]; // 保存请求结果
                this._data = {
                    threadlevel: this._curLevel,
                    limit: 0,
                    tim: this._times[this._curLevel]
                };
            },

            _initUI: function () {
                if(this._container) return;
                this._container = $('<div class="row threatLevelContainer"></div>');
                this._container.html(this.getContentHTML());
                $('body').append(this._container);
            },

            _initEvts: function () {
                var self = this;
                var $container = this._container;
                var $collapseDiv = $container.find('.collapseDiv');
                $container.find('ul>li').on('click', function () {
                    var $this = $(this);
                    self._popPanel && self._popPanel.remove();
                    if($this.hasClass('active')) { // 收起
                        $this.removeClass('active');
                        if(self._popPanel) {
                            self._popPanel.remove();
                        }
                        $collapseDiv.height(0);
                        self._times[self._curLevel] = self.dateTimeUtil.getCurrentUnixTime();
                        self.sendAjaxI(self._curLevel, self.config.url, self.getAjaxData());
                        self._curLevel = 0;
                    } else { // 展开
                        $this.addClass('active').siblings().removeClass('active');
                        self._curLevel = +$this.data('level');
                        $collapseDiv.height(320);
                        $collapseDiv.find('.table' + self._curLevel).css('display', 'block').siblings().css('display', 'none');
                        self.stopIFlashing();
                        self._times[self._curLevel] = self.dateTimeUtil.getCurrentUnixTime();
                        self.sendAjaxI(self._curLevel, self.config.url, self.getAjaxData());
                    }
                });
            },

            stopIFlashing:function (){
              var $msg = this._container.find(".nav  .level" + this._curLevel + "  .badge");
              $msg.stopFlashing();
              $msg.data('allcount', this._resData[this._curLevel].length);
              $msg.data('unreadcount', 0);
              $msg.html(0 + '/' + this._resData[this._curLevel].length);
            },

            getContentHTML: function () {
                var html = [];
                html.push('<div class="collapseDiv">');
                html.push('<div class="tableDiv table1"></div>');
                html.push('<div class="tableDiv table2"></div>');
                html.push('<div class="tableDiv table3"></div>');
                html.push('<div class="tableDiv table4"></div>');
                html.push('</div>');
                html.push('<ul class="nav nav-pills" role="tablist">');
                html.push('<li role="presentation" class="level1" data-level="1"><a href="#">最高等级 <span class="badge">--/--</span></a></li>');
                html.push('<li role="presentation" class="level2" data-level="2"><a href="#">第二等级 <span class="badge">--/--</span></a></li>');
                html.push('<li role="presentation" class="level3" data-level="3"><a href="#">第三等级 <span class="badge">--/--</span></a></li>');
                html.push('<li role="presentation" class="level4" data-level="4"><a href="#">第四等级 <span class="badge">--/--</span></a></li>');
                html.push('</ul>');
                return html.join('');
            },

            _ajaxCallback1: function (res) {
                this._ajaxCompelets[1] = 1;
                var list = res && res.msg && res.msg.shipList || [];
                if (!list.length)  {
                  this._updateTableI(1,[]);
                  return;
                }
                var insertList = [];
                var timeField = "tim";
                var oldmax = this._resData[1].length ? this._resData[1][0][timeField] : list[list.length-1][timeField];
                var newmax = list[0][timeField];
                // 提取出 oldmax 之后的记录
                for (var i = 0 , len = list.length; i < len; i++){
                    if (list[i][timeField] >= oldmax) {
                        insertList.push(list[i]);
                        break;
                    }
                }
                // update data
                this._resData[1] = insertList.concat(this._resData[1]);
                // 表格
                this._updateTableI(1,insertList);
                // update html
                var $msg = this._container.find(".nav  .level1  .badge");
                // 消息
                var allcount = +$msg.data('allcount');
                var unreadcount = +$msg.data('unreadcount');
                if (this._curLevel === 1) {
                    // if (insertList.length){
                    //     $msg.startFlashing();
                    // } else {
                    //     $msg.stopFlashing();
                    // }
                    // $msg.html(insertList.length + '/' + this._resData[1].length);
                    $msg.data('allcount', this._resData[1].length);
                    $msg.data('unreadcount', 0);
                    $msg.html(0 + '/' + this._resData[1].length);
                } else {
                    if (insertList.length){
                        $msg.startFlashing();
                        if(!isNaN(unreadcount)) {
                          unreadcount += insertList.length;
                        } else {
                          unreadcount = insertList.length;
                        }
                        $msg.data('allcount', this._resData[1].length);
                        $msg.data('unreadcount', unreadcount);
                        $msg.html(unreadcount + '/' + this._resData[1].length);
                    }
                }
            },

            _ajaxCallback2: function (res) {
                this._ajaxCompelets[2] = 1;
                var list = res && res.msg && res.msg.shipList || [];
                if (!list.length)  {
                  this._updateTableI(2,[]);
                  return;
                }
                var insertList = [];
                var timeField = "tim";
                var oldmax = this._resData[2].length ? this._resData[2][0][timeField] : list[list.length-1][timeField];
                var newmax = list[0][timeField];
                for (var i = 0 , len = list.length; i < len; i++){
                    if (list[i][timeField] >= oldmax) {
                        insertList.push(list[i]);
                        break;
                    }
                }
                // update data
                this._resData[2] = insertList.concat(this._resData[2]);
                // 表格
                this._updateTableI(2,insertList);
                // update html
                var $msg = this._container.find(".nav  .level2  .badge");
                // 消息
                var allcount = +$msg.data('allcount');
                var unreadcount = +$msg.data('unreadcount');
                if (this._curLevel === 2) {
                    // if (insertList.length){
                    //     $msg.startFlashing();
                    // } else {
                    //     $msg.stopFlashing();
                    // }
                    // $msg.html(insertList.length + '/' + this._resData[2].length);
                    $msg.data('allcount', this._resData[2].length);
                    $msg.data('unreadcount', 0);
                    $msg.html(0 + '/' + this._resData[2].length);
                } else {
                    if (insertList.length){
                        $msg.startFlashing();
                        if(!isNaN(unreadcount)) {
                          unreadcount += insertList.length;
                        } else {
                          unreadcount = insertList.length;
                        }
                        $msg.data('allcount', this._resData[2].length);
                        $msg.data('unreadcount', unreadcount);
                        $msg.html(unreadcount + '/' + this._resData[2].length);
                    }
                }
            },

            _ajaxCallback3: function (res) {
                this._ajaxCompelets[3] = 1;
                var list = res && res.msg && res.msg.shipList || [];
                if (!list.length)  {
                  this._updateTableI(3,[]);
                  return;
                }
                var insertList = [];
                var timeField = "tim";
                var oldmax = this._resData[3].length ? this._resData[3][0][timeField] : list[list.length-1][timeField];
                var newmax = list[0][timeField];
                for (var i = 0 , len = list.length; i < len; i++){
                  if (list[i][timeField] >= oldmax) {
                      insertList.push(list[i]);
                      break;
                  }
                }
                // update data
                this._resData[3] = insertList.concat(this._resData[3]);
                // 表格
                this._updateTableI(3,insertList);
                // update html
                var $msg = this._container.find(".nav  .level3  .badge");
                // 消息
                var allcount = +$msg.data('allcount');
                var unreadcount = +$msg.data('unreadcount');
                if (this._curLevel === 3) {
                    // if (insertList.length){
                    //     $msg.startFlashing();
                    // } else {
                    //     $msg.stopFlashing();
                    // }
                    // $msg.html(insertList.length + '/' + this._resData[3].length);
                    $msg.data('allcount', this._resData[3].length);
                    $msg.data('unreadcount', 0);
                    $msg.html(0 + '/' + this._resData[3].length);
                } else {
                    if (insertList.length){
                        $msg.startFlashing();
                        if(!isNaN(unreadcount)) {
                          unreadcount += insertList.length;
                        } else {
                          unreadcount = insertList.length;
                        }
                        $msg.data('allcount', this._resData[3].length);
                        $msg.data('unreadcount', unreadcount);
                        $msg.html(unreadcount + '/' + this._resData[3].length);
                    }
                }
            },

            _ajaxCallback4: function (res) {
                this._ajaxCompelets[4] = 1;
                var list = res && res.msg && res.msg.shipList || [];
                if (!list.length)  {
                  this._updateTableI(4,[]);
                  return;
                }
                var insertList = [];
                var timeField = "tim";
                var oldmax = this._resData[4].length ? this._resData[4][0][timeField] : list[list.length-1][timeField];
                var newmax = list[0][timeField];
                for (var i = 0 , len = list.length; i < len; i++){
                  if (list[i][timeField] >= oldmax) {
                      insertList.push(list[i]);
                      break;
                  }
                }
                // update data
                this._resData[4] = insertList.concat(this._resData[4]);
                // 表格
                this._updateTableI(4,insertList);
                // update html
                var $msg = this._container.find(".nav  .level4  .badge");
                // 消息
                var allcount = +$msg.data('allcount');
                var unreadcount = +$msg.data('unreadcount');
                if (this._curLevel === 4) {
                    // if (insertList.length){
                    //     $msg.startFlashing();
                    // } else {
                    //     $msg.stopFlashing();
                    // }
                    // $msg.html(insertList.length + '/' + this._resData[4].length);
                    $msg.data('allcount', this._resData[4].length);
                    $msg.data('unreadcount', 0);
                    $msg.html(0 + '/' + this._resData[4].length);
                } else {
                    if (insertList.length){
                        $msg.startFlashing();
                        if(!isNaN(unreadcount)) {
                          unreadcount += insertList.length;
                        } else {
                          unreadcount = insertList.length;
                        }
                        $msg.data('allcount', this._resData[4].length);
                        $msg.data('unreadcount', unreadcount);
                        $msg.html(unreadcount + '/' + this._resData[4].length);
                    }
                }
            },

            _updateTableI: function (index, insertData) {
                var $tableDiv = this._container.find(".collapseDiv .table" + index);
                if ($tableDiv.html() === '') {
                    $tableDiv.html(this.getTableHTML(insertData));
                } else {
                    $tableDiv.find(".tbDiv  table").prepend(this.getTableTrsHTML(insertData));
                }
                $tableDiv.find('.tbDiv').mCustomScrollbar({ theme: "minimal-dark" });
                this._initTableEvts($tableDiv);
            },

            _initTableEvts: function ($tableDiv) {
                var self = this;
                $tableDiv.find('.btn-link').on('click', function (e) {
                    if(self._popPanel) {
                        self._popPanel.remove();
                    }
                    if (self._detailAjax){
                      self._detailAjax.abort();
                    }
                    var $this = $(e.currentTarget).parent().parent();
                    var tid = $this.data('tid');
                    var msi = $this.data('msi');
                    var sn = $this.data('sn');
                    var imo = $this.data('imo');
                    var cs = $this.data('cs');
                    self._clickRowData = {
                      tid: tid,
                      msi: msi,
                      sn: sn,
                      imo: imo,
                      cs: cs
                    };
                    var options = {
                        title: '详细信息',
                        width: 570,
                        height: 320,
                        left: 670,
                        top: 160,
                        // ismodal:true,
                        scroll: true,
                        contentHTML: self.getDetailContentHtml()
                    };
                    self._popPanel = new L.ICT.PopPanel(options).show();
                    self._popPanel.on("popPanelRemove", function () {
                        this._popPanel = null;
                        this._detailAjax && this._detailAjax.abort();
                    }, self);
                    self.getDetailInfo(tid);
                });
            },

            getDetailInfo: function (tid){
               var url1 = this.config.detailUrl1;
               var url2 = this.config.detailUrl2;
               var data1 = {
                 tid: tid
               };
               var data2 = {
                 ship_name: self._clickRowData.sn ? self._clickRowData.sn : 'N',
                 mmsi: self._clickRowData.msi,
                 imo: self._clickRowData.imo ? self._clickRowData.imo : 0,
                 call_sign: self._clickRowData.cs ?  self._clickRowData.cs : 'N'
               };
               var $detailContainer = this._popPanel && this._popPanel.getContainer();
               // 获取异常信息
               this._detailAjax.post(url1, data1, true, this, function (res, error) {
                  if (error || res.state !== 1 || !res.msg.list) {
                    return ;
                  }
                  var html = this.getAbnormalHtml(res.msg.list);
                  this._popPanel && $detailContainer.find('.table_ycxx tbody').html(html);
               });
               // 获取违规记录信息
               this._detailAjax.post(url2, data2, true, this, function (res, error) {
                  if (error || res.state !== 1 || !res.msg.list) {
                    return ;
                  }
                  var html = this.getIllegalHtml(res.msg.list);
                  this._popPanel && $detailContainer.find('.table_wgjl tbody').html(html);
               });
            },

            getDetailContentHtml: function () {
              var html = [];
              html.push('<div class="threadlevel_detailInfoDiv">');

              /***************************** panel-基本信息  ******************************/
              html.push('<div class="panel panel-default">');
              // head
              html.push('<div class="panel-heading">基本信息：</div>');
              // table
              html.push('<table class="table table_jbxx">');
              html.push('<tr><th>批号</th><th>MMSI</th><th>船名</th><th>呼号</th><th>IMO</th></tr>');
              html.push('<tbody>');
              html.push('<tr>');
              html.push('<td>' + this._clickRowData.tid + '</td>');
              html.push('<td>' + this._clickRowData.msi + '</td>');
              html.push('<td>' + this._clickRowData.sn + '</td>');
              html.push('<td>' + this._clickRowData.co + '</td>');
              html.push('<td>' + this._clickRowData.imo + '</td>');
              html.push('</tr>');
              html.push('</tbody>');
              html.push('</table>');
              html.push('</div>');

              /*****************  panel-异常信息 ******************************/
              html.push('<div class="panel panel-default">');
              // head
              html.push('<div class="panel-heading">异常信息：</div>');
              // table
              html.push('<table class="table table_ycxx">');
              html.push('<tr><th>时间</th><th>详细信息</th></tr>');
              html.push('<tbody></tbody>');
              html.push('</table>');
              html.push('</div>');

              /*********** panel-违规记录 *****************************/
              html.push('<div class="panel panel-default">');
              // head
              html.push('<div class="panel-heading">违规记录：</div>');
              // table
              html.push('<table class="table table_wgjl">');
              html.push('<tr><th>时间</th><th>详细信息</th></tr>');
              html.push('<tbody></tbody>');
              html.push('</table>');
              html.push('</div>');

              html.push('</div>');
              return html.join('');
            },

            getAbnormalHtml:function (data) {
              var html =[];
              var i, len, time, lon, lat, atp, str;
              for(i = 0, len = data.length; i < len; i++){
                time = L.ict.app.util.dateTime.getTimeStrFromUnix(data[i].tim);
                lon = L.ict.app.util.tool.latlngTodfmStr(data[i].lon / 600000, "lng");
                lat = L.ict.app.util.tool.latlngTodfmStr(data[i].lat / 600000, "lat");
                atp = data[i].atp;
                str = [];
                str.push('经度：' + lon + '，');
                str.push('纬度：' + lat + '，');
                str.push('异常类型：' + atp + '，');
                if (atp === 1) {
                  str.push('航速：' + Number(data[i].cog / 10).toFixed(1) );
                } else if (atp === 2) {
                  str.push('静默时间：' + data[i].offs + '秒');
                } else {
                  str.push('区域名称：' + data[i].area + '，');
                  str.push('区域ID：' + data[i].rid + '，');
                  str.push( data[i].type === 1 ? '进入区域' : data[i].type === 2 ? '离开区域' : '');
                }
                html.push('<tr>');
                html.push('<td>' + time + '</td>');
                html.push('<td>' + str.join('') + '</td>');
                html.push('</tr>');
              }
              return html.join('');
            },

            getIllegalHtml: function (data) {
              var html =[];
              var i , len, time, level, str;
              for(i = 0, len = data.length; i < len; i++){
                time = L.ict.app.util.dateTime.getTimeStrFromUnix(data[i].tim);
                level = ( data[i].vic === 15 ? '无威胁' : data[i].vic );
                str = [];
                str.push('ID：' + data[i].id + '，');
                str.push('呼号：' + data[i].cs + '，');
                str.push('国别：' + data[i].fla.repalce(/@/g, '') + '，');
                str.push('IMO：' + data[i].imo + '，');
                str.push('MMSI：' + data[i].msi + '，');
                str.push('船名：' + data[i].sn + '，');
                str.push('违规等级：' + level + '，');
                str.push('违规事件：' + data[i].vio);
                html.push('<tr>');
                html.push('<td>' + time + '</td>');
                html.push('<td>' + str.join('') + '</td>');
                html.push('</tr>');
              }
              return html.join('');
            },

            getTableHTML: function (data) {
                var html = [];
                // 表头
                html.push('<div class="thDiv">');
                html.push('<table>');
                html.push('<tr><td>批号</td><td>MMSI</td><td>船名</td><td>IMO</td><td>呼号</td><td>详细信息</td></tr>');
                html.push('</table>');
                html.push('</div>');
                // 表身
                html.push('<div class="tbDiv">');
                html.push('<table>');
                html.push(this.getTableTrsHTML(data));
                html.push('</table>');
                html.push('</div>');
                return html.join('');
            },

            getTableTrsHTML: function (data) {
                var html = [];
                for (var i =0, len = data.length; i < len; i++){
                    var obj = data[i];
                    html.push('<tr data-tid="' + obj.tid + '" data-msi="' + obj.msi + '" data-sn="' + obj.sn + '" data-imo="' + obj.imo + '" data-cs="' + obj.cs + '">');
                    html.push('<td>'+ obj.tid +'</td>');
                    html.push('<td>'+ obj.msi +'</td>');
                    html.push('<td>'+ obj.sn +'</td>');
                    html.push('<td>'+ obj.imo +'</td>');
                    html.push('<td>'+ obj.cs +'</td>');
                    html.push('<td><button type="button" class="btn btn-link">查看</button></td>');
                    html.push('</tr>');
                }
                return html.join('');
            },

            sendAjaxOne:function (){
              $.when(this.sendAjax(1, this.config.url, this.getAjaxData(1)),
               this.sendAjax(2, this.config.url, this.getAjaxData(2)),
               this.sendAjax(3, this.config.url, this.getAjaxData(3)),
               this.sendAjax(4, this.config.url, this.getAjaxData(4)))
               .always(function (){
                  this._firstCompelete = true;
               }.bind(this));
            },

            sendAjax(index, url, data, callback){
              var ajax = this._ajaxs[index];
              var ajaxCallback = this._ajaxCallbacks[index];
              return ajax.post(url, data, true, this, callback ? callback : ajaxCallback);
            },

            sendAjaxI: function (index, url, data, callback) {
                var ajax = this._ajaxs[index];
                var ajaxCallback = this._ajaxCallbacks[index];
                var interval = this._intervals[index];
                if (this._firstCompelete){
                  ajax.abort();
                  this._ajaxCompelets[index] = 0;
                  ajax.post(url, data, true, this, callback ? callback : ajaxCallback);
                  interval && window.clearInterval(interval);
                  this._intervals[index] = window.setInterval(function () {
                      if(this._ajaxCompelets[index] === 1) {
                          this._ajaxCompelets[index] = 0;
                          ajax.post(url, data, true, this, callback ? callback : ajaxCallback);
                      }
                  }.bind(this), this.config.updateTime);
                }
            },

            getAjaxData: function (curlevel) {
                var index = curlevel ? curlevel : this._curLevel;
                return {
                    threadlevel: index,
                    limit: 0,
                    tim: this._times[index]
                };
            },

            clearIntervals: function () {
               if (this._intervals && this._intervals.length){
                 this._intervals.forEach(function (val, index, arr) {
                     window.clearInterval(val);
                     arr[index] = null;
                 });
               }
            },

            stopAjaxs: function () {
              if (this._ajaxs && this._ajaxs.length){
                this._ajaxs.forEach(function (val, index, arr) {
                    if(val instanceof L.ICT.Ajax) {
                        val.abort();
                    }
                });
              }
            }

        })
    });
});
